#include "mline.h"
#ifdef GUI_APPLICATION

#include "geometry/mpoint.h"
#include "mmath.h"

static inline void getCoefficient(mreal &k, mreal &b, const MLine &line)
{
	k = (line.point1().y() - line.point2().y()) /
		(line.point1().x() - line.point2().x());
	b = line.point1().y() - k * line.point2().x();
}

void MLine::setLine(int x0, int y0, int x1, int y1)
{
	p0.move(x0, y0);
	p1.move(x1, y1);
}

void MLine::setLine(const MPoint &point0, const MPoint &point1)
{
	p0.move(point0);
	p1.move(point1);
}

void MLine::setLine(const MLine &other)
{
	p0.move(other.p0);
	p1.move(other.p1);
}

bool MLine::isOnLine(const MPoint &point) const
{
	mreal k, b;
	getCoefficient(k, b, *this);
	return point.y() == static_cast<int>(k * point.x() + b + 0.5);
}

bool MLine::isOnLine(int x, int y) const
{
	mreal k, b;
	getCoefficient(k, b, *this);
	return y == static_cast<int>(k * x + b + 0.5);
}

const MLine &MLine::operator=(const MLine &other)
{
	p0 = other.p0;
	p1 = other.p1;
	return *this;
}

bool MLine::operator&(const MLine &other) const
{
	mreal k0, b0;
	getCoefficient(k0, b0,  *this);

	mreal k1, b1;
	getCoefficient(k1, b1, other);

	int poi_x = (b1 - b0) / (k0 - k1);
	int poi_y = k0 * poi_x + b0;

	return isOnLine(poi_x, poi_y) and other.isOnLine(poi_x, poi_y);
}


#endif //GUI_APPLICATION
